<template>
	<!-- <u-navbar title="查询分页列表" bgColor="#FBFBFF" :autoBack="true" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
	</u-navbar> -->
	<view class="baseForm">
		<u--form labelPosition="left" labelWidth="120px">
			<u-form-item label="扫码物料条形码">
				<!-- 条码录入 -->
				<scan-bar ref="scanBarRef" @code-scanned="getScanResult" class="scan-bar"></scan-bar>
			</u-form-item>
		</u--form>
		<!-- 卡片显示 -->
		<text class="list-title">列表信息({{ total }})</text>
		<view class="activeHeight">
			<!-- 列表 -->
			<u-list @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight"
				lowerThreshold="100px">
				<u-list-item v-for="(item, index) in materialReturnList" :key="item.id">
					<view class="card">
						<view class="title">
							<view style="line-height:22px; word-break: break-all;">物料编码:
								{{ item?.returnBarcode || "" }}
							</view>
						</view>
						<view class="body">
							<view class="content">
								<view class="des">物料:
									{{ item?.materialCode + "-" + item?.materialName || 0 }}
								</view>
								<view class="des">包装编码：{{ item?.returnCode || " " }}</view>
								<view class="des">退货数量：{{ item?.returnQuantity || 0 }}</view>
								<view class="des">退货时间：{{ item?.createTime || "待定" }}</view>

							</view>
							<button class="uni-btn" size="mini" plain type="primary"
								@click="selectWorkOrder(item, index)">打印</button>
							<button v-show="item?.isReturn" class="uni-btn" size="mini" type="primary">
								已退
							</button>
							<button v-show="!item?.isReturn" class="uni-btn" size="mini" plain type="primary">
								退中
							</button>
							<!-- <view class="des">材质：{{ item?.materialName || '待定' }}</view> -->
							<!-- <view class="des">炉号：{{ item?.planFinishQuantity || 0 }}</view> -->
							<!-- <view class="des">单位：{{ item?.quantityUnit?.split(' ')[0] || '待定' }}</view> -->
							<!-- <view class="des">退货物料条形码：{{ item?.returnBarcode || '' }}</view> -->
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<web-view
			ref="webview"
			v-if="showWebView"
			:src="webviewSrc"
			:update-title="false"
			:webview-styles="{
				width: '0px',
				height:'0px',
			}"
			style="height:0px;width:0px;background-color: aquamarine;"
			@message="message"
		></web-view>
		<u-modal :show="showImport" ref="uModal" :content="`当前物料编码为${selectOrder?.returnBarcode ?? ''}, 请确认是否打印？`"
			confirmText="打印" showCancelButton :asyncClose="true" @cancel="cancelImport"
			@confirm="confirmImport(selectOrder.id)"></u-modal>
	</view>
	<u-back-top :scroll-top="scrollTop" top="200" mode="squery"></u-back-top>
</template>

<script lang="ts" setup>
    import { computed, ref, watch } from 'vue';
	import { onPageScroll, onPullDownRefresh, onShow } from "@dcloudio/uni-app";
	import ScanBar from "@/components/scan-bar/index.vue";
	import { http } from "@/utils/http";
	import { PageResult } from "@/types/type";
	import { useUserStore } from "../../../stores/useUserStore";
	// 监听页面到顶部距离
	const scrollTop = ref(0);
	//列表高度
	const listHeight = ref('');
	const scrolltolower = () => {
		totalPage.value > current.value && getMaterialReturnList();
	};
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop;
	});
	onShow(async () => {
		// #ifdef H5
		listHeight.value = 'calc(100vh - 88px)';
		// #endif

		// #ifdef APP-PLUS
		listHeight.value = 'calc(100vh - 44px)';
		// #endif
		reset();
		getMaterialReturnList();
	});
	// 选择订单
	const selectOrder = ref({});
	const selectIndex = ref();
	const showImport = ref(false);
	const showWebView = ref(false);
	function selectWorkOrder(row, index) {
		showWebView.value = true;
		const defaultPrinter = computed(() => (useUserStore().defaultPrinter ? JSON.parse(useUserStore().defaultPrinter) : ''));
		console.log("111",defaultPrinter.value.printerName);
		if (defaultPrinter.value.length==0)
		{
		uni.showToast({
			title: '请选择打印设备',
			icon: 'error'
		});
		return false;
		}
		else
		{
		showImport.value = true;
		selectOrder.value = row;
		selectIndex.value = index;
		}
	}
	// 取消选择订单
	function cancelImport() {
		showImport.value = false;
		selectOrder.value = {};
		selectIndex.value = null;
	}
	// 获取扫码结果
	async function getScanResult(result : string) {
		// 获取code码详细信息，并进行赋值
		reset();
		// code.value = result;
		if (!result) {
			getMaterialReturnList();
			return;
		}
		scanBarRef.value.reset();
		//外购
		const res : any = await http({
			method: "POST",
			url: "/mes/mesproducingstock/getList",
			data: {
				workCenterId: loginWorkInfo.value.workCenterId,
				materialBarcode: result,
				materialQuantity: 0,
				isValid: 1,
				stockFrom: 0,
			},
		});
		if (res.data.length > 0) {
			jumpToDetail(res.data[0]);
		} else {
			uni.$u.toast("未找到物料信息！");
			getMaterialReturnList();
		}
	}
	onPullDownRefresh(() => {
		current.value = 0;
		materialReturnList.value = [];
		getMaterialReturnList("refresh");
	});
	// 跳转至详情页面
	function jumpToDetail(res : any) {
		uni.navigateTo({
			url: `/pages/produce/materialReturn/detail?result=${JSON.stringify(res)}`,
			animationDuration: 0,
		});
	}

	// 请求列表参数定义
	const materialReturnList = ref([]); // 缺货要货集合
		const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	const current = ref(0); // 当前页
	const totalPage = ref(0); //累计分页
	const total = ref(0); // 累计条数
	const scanBarRef = ref();
	const url = process.env.VITE_APP_WEBVIEW;
	const webviewSrc = ref(url);
	function confirmImport(id) {
		console.log("111",id);
		const defaultPrinter = computed(() => JSON.parse(useUserStore().defaultPrinter));
		const loginWorkInfoName = computed(() => useUserStore().userInfo.userName);
		console.log("222",loginWorkInfoName.value);
		setTimeout(()=>{
			webviewSrc.value = `${url}iframePrintReturn?id=${id}&printer=${defaultPrinter.value.printerName}&printername=${loginWorkInfoName.value}`
			console.log(webviewSrc.value)
		},1000)
	}

	// 初始化参数
	function reset() {
		current.value = 0;
		materialReturnList.value = [];
		total.value = 0;
		totalPage.value = 0;
	}
	//打印
	watch(()=>showImport.value,(newValue)=>{
		if (newValue === false) {
			showWebView.value = false;
			webviewSrc.value = url;
			selectOrder.value = {};
		}
	})
	// webview向外部发送消息
	function message(event) {
		console.log("event",event)
		showImport.value = false;
		const data = event.detail.data[0];
		if (data.code === 200) {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
		} else {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
		}
		console.log("接收到消息：" + JSON.stringify(event.detail.data));
	}
	async function getMaterialReturnList(type ?: string) {
		try {
			current.value += 1;
			const result : PageResult<any> = await http({
				method: "POST",
				url: "/mes/mesmaterialreturn/queryByPage",
				data: {
					current: current.value,
					size: 20,
					data: {
						workCenterId: loginWorkInfo.value.workCenterId,
						remarks: 0,
					},
				},
			});
			let list = result.data
			for (let i = 0; i < list.length; i++) {
				materialReturnList.value.push(list[i]);
			}
			total.value = result.total;
			totalPage.value = result.page;
			type === "refresh" && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
</script>

<style lang="scss" scoped>
	.baseForm {
		:deep(.uni-scroll-view) {
			overflow: inherit;
		}

		.u-form {
			padding: $uni-page-padding;

			:deep(.u-form-item__body) {
				padding: 5px 0;
			}

			.u-input {
				border: 1px solid $uni-input-border-color;
			}

			.scan-bar {
				margin-top: 5px;
				display: flex;
				flex: 1;
			}
		}

		.u-line {
			padding: 10px 0;
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1;
				}

				&:nth-child(2) {
					flex: 3;
				}
			}
		}

		.list-title {
			line-height: 40px;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.4);
			margin-left: 15px;
		}

		.list {
			.card {
				margin: $uni-page-padding;
				margin-top: 5px;
				margin-bottom: 5px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				flex-direction: column;
				transition: all 300ms ease;
				box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
				background-color: #fff;

				.title {
					box-sizing: border-box;
					display: flex;
					align-items: center;
					justify-content: space-between;
					width: 100%;
					padding: 0 6px;
					font-size: 14px;
					font-weight: bolder;
					line-height: 40px;
					height: 40px;
					margin-top: 4px;
					color: #101010;
					border-bottom: 1px solid #e5ebff;
				}

				.uni-btn {
					float: right;
					font-size: 12px;
					height: 24px;
					line-height: 24px;
					padding: 0 15px;
					font-weight: 400;
					margin: 0;
				}

				.body {
					display: flex;
					align-self: center;
					justify-content: space-between;
					width: 100%;
					padding: 0 6px;
					box-sizing: border-box;

					.content {
						.des {
							font-size: 12px;
							line-height: 20px;
							height: 20px;
							margin-bottom: 3px;
						}
					}
				}
			}
		}
	}
</style>